<template>
  <div class="p-2 container">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="访客姓名" prop="visitorName">
              <el-input v-model="queryParams.visitorName" placeholder="请输入访客姓名" clearable style="width: 200px;" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="访客单位" prop="visitorDeptName">
              <el-input v-model="queryParams.visitorDeptName" placeholder="请输入访客单位" clearable style="width: 200px;" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="来访时间" prop="reservationStartTime">
              <el-date-picker clearable
                v-model="queryParams.reservationStartTime"
                type="date"
                style="width: 200px;"
                value-format="YYYY-MM-DD"
                placeholder="请选择预约开始时间"
              />
            </el-form-item>

            <el-form-item label="访客类型" prop="visitorType">
              <el-select v-model="queryParams.visitorType" placeholder="请选择访客类型" clearable @keyup.enter="handleQuery" >
                <el-option label="供应商" value="1"></el-option>
                <el-option label="拜访" value="2"></el-option>
                <el-option label="其他" value="3"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择访客类型" clearable @keyup.enter="handleQuery" >
                <el-option label="待申请" value="0"></el-option>
                <el-option label="待审核" value="1"></el-option>
                <el-option label="审核中" value="2"></el-option>
                <el-option label="通过" value="3"></el-option>
                <el-option label="驳回" value="4"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="申请时间" prop="reservationEndTime">
              <el-date-picker clearable
                v-model="queryParams.reservationEndTime"
                type="date"
                style="width: 200px;"
                value-format="YYYY-MM-DD"
                placeholder="请选择申请时间"
              />
            </el-form-item>
            <el-form-item label="申请编号" prop="visitAddress">
              <el-input v-model="queryParams.visitAddress" placeholder="请输入申请编号" clearable style="width: 200px;" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never" style="flex: 1; display: flex; flex-direction: column; position: relative">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['visitor:visitor-apply-invite:add']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
          <right-toolbar @queryTable="getList" v-model:showSearch="showSearch"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="visitorApplyInviteList" height="calc(100% - 30px)" @selection-change="handleSelectionChange">
        <el-table-column label="序号" type="index" width="55" align="center" />
        <el-table-column label="申请编号" align="center" prop="applyCode" show-overflow-tooltip />
        <el-table-column label="访客姓名" align="center" prop="visitorName" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.visitorNameList }}</span>
          </template>
          </el-table-column>
        <el-table-column label="访客单位" align="center" prop="visitorDeptName" show-overflow-tooltip>
          <template #default="scope">
            <span>{{  scope.row.visitorDeptNameList }}</span>
          </template>
          </el-table-column>
        <el-table-column label="来访地点" align="center" prop="visitReason" show-overflow-tooltip >
          <template #default="scope">
            <span>A栋602</span>
            <!-- <span>{{ scope.row.parkBuildingName === null ? '-' : scope.row.parkBuildingName }}/
                  {{ scope.row.parkBuildingAreaName === null ? '-' : scope.row.parkBuildingAreaName }}/
                  {{ scope.row.parkBuildingFloorName === null ? '-' : scope.row.parkBuildingFloorName }}/
                  {{ scope.row.parkBuildingRoomName === null ? '-' : scope.row.parkBuildingRoomName }}</span> -->
          </template>
        </el-table-column>
        <el-table-column label="来访时间" align="center" prop="startTime" show-overflow-tooltip width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }} ~ {{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="访客类型" align="center" prop="visitorType" show-overflow-tooltip width="100">
<!--          <template #default="scope">-->
<!--            <span v-if="scope.row.visitorDerageFlag === 1">成人</span>-->
<!--            <span v-if="scope.row.visitorDerageFlag === 2">儿童</span>-->
<!--            <span v-if="scope.row.visitorDerageFlag === 3">老人</span>-->
<!--          </template>-->
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status" width="100">
          <template #default="scope">
            <span v-if="scope.row.status === 0">待申请</span>
            <span v-if="scope.row.status === 1">待审核</span>
            <span v-if="scope.row.status === 2">审核中</span>
            <span v-if="scope.row.status === 3">通过</span>
            <span v-if="scope.row.status === 4">驳回</span>
          </template>
        </el-table-column>
        <el-table-column label="申请时间" align="center" prop="applyTime" show-overflow-tooltip width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.applyTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
          <template #default="scope">
            <el-tooltip content="查看" placement="top">
              <el-button v-hasPermi="['visitor:visitor-record:edit']" link type="primary" @click="handleDetails(scope.row)">查看</el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['visitor:visitor-apply-invite:remove']" link type="primary" @click="handleDelete(scope.row)" >删除</el-button>
            </el-tooltip>
            <el-tooltip content="提交申请" placement="top" >
              <el-button v-if="scope.row.status == 0 || scope.row.status == 'draft'" v-hasPermi="['visitor:visitor-apply-invite:edit']" link type="primary" @click="handleSubmit(scope.row)">提交申请</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 提交组件 -->
    <submitVerify ref="submitVerifyRef" :task-variables="taskVariables" @submit-callback="submitCallback" />
    <!-- 添加或修改访客申请邀约对话框 -->
    <el-drawer v-model="dialog.shouAdd" :title="dialog.title" append-to-body size="900px" destroy-on-close>
    <add
      :visible="dialog.shouAdd"
      :title="dialog.title"
      :form="form"
      :rules="rules"
      :buildingRoomList="buildingRoomList"
      :buttonLoading="buttonLoading"
      :dk-msg='dkMsg'
      @close="dialog.shouAdd = false"
      @submit="getList"
    />
    </el-drawer>
    <!-- 查看访客申请邀约对话框 -->
    <el-drawer v-model="dialog.details" :title="dialog.title" append-to-body size="900px">
      <detail
      :visible="dialog.details"
      :title="dialog.title"
      :visitorApplyInviteInfo="visitorApplyInviteInfo"
      :rules="rules"
      :visitorUserList="visitorUserList"
      @close="dialog.details = false"
    />
    </el-drawer>
    <!--访客提交申请选择审批人-->
    <el-drawer v-model="dialog.audit" :title="dialog.title" append-to-body size="500px">
      <el-form
        ref="visitorApplyInviteFormRef"
        :model="auditForm"
        :rules="auditRules"
        :inline="true"
        label-width="120px"
        style="display: flex; justify-content: space-around"
      >
        <div>
          <div class="border-box" style="width: 400px">
            <el-form-item label="审批人：" prop="auditUserId">
              <el-select v-model="auditForm.auditUserId" filterable clearable placeholder="请选择审批人">
                <el-option v-for="item in areaUserList" :key="item.userId" :label="item.userName" :value="item.userId" />
              </el-select>
            </el-form-item>

            <el-form-item label="备注：" prop="remark">
              <el-input v-model="auditForm.remark" placeholder="请输入" style="width: 200px" />
            </el-form-item>
          </div>
        </div>


      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitAuditForm()">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup name="visitorApplyInvite" lang="ts">
import {
  addvisitorApplyInvite,
  delvisitorApplyInvite,
  getvisitorApplyInvite,
  listvisitorApplyInvite,
  updatevisitorApplyInvite
} from '@/api/access/visitor/visitor-apply-invite';
import { userInfoVo, visitorApplyInviteForm, visitorApplyInviteQuery, visitorApplyInviteVO } from '@/api/access/visitor/visitor-apply-invite/types';
import { listUserInfo } from '@/api/access/user/user-info';
import { visitorAuditForm } from '@/api/access/visitor/visitor-audit/types';
import { addvisitorAudit } from '@/api/access/visitor/visitor-audit';
import { listparkBuildingRoom } from '@/api/park/park-building-room';
import useUserStore from '@/store/modules/user';
import request from '@/utils/request';
import { listUser } from '@/api/system/user';
import { UserVO } from '@/api/system/user/types';
import add from './components/add.vue';
import detail from './components/detail.vue';
import { StartProcessBo } from '@/api/workflow/workflowCommon/types';
import { startWorkFlow } from '@/api/workflow/task';
import SubmitVerify from '@/components/Process/submitVerify.vue';

// 新增打开弹窗
let dkMsg = false

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const userStore = useUserStore();
const visitorApplyInviteList = ref<visitorApplyInviteVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const areaUserList = ref<userInfoVo[]>([]);
const userList = ref<UserVO[]>([]);
const visitorApplyInviteInfo = ref();
const visitorUserList = ref([]);
const taskVariables = ref<Record<string, any>>({});
const buildingRoomList = ref([]);
//提交组件
const submitVerifyRef = ref<InstanceType<typeof SubmitVerify>>();
const applyLoading = ref(false);

const queryFormRef = ref<ElFormInstance>();
const visitorApplyInviteFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: '',
  audit: false
});

const submitFormData = ref<StartProcessBo>({
  businessKey: '',
  tableName: '',
  variables: {}
});

const initFormData: visitorApplyInviteForm = {
  visitorApplyInviteId: undefined,
  remark: undefined,
  type: undefined,
  visitReason: undefined,
  inviteUserId: undefined,
  startTime: undefined,
  endTime: undefined,
  visitorType: undefined,
  visitorList: [],
  status: undefined,
  applyUserId: undefined
};

const initAuditFormData: visitorAuditForm = {
  visitorApplyInviteId: undefined,
  remark: undefined,
  auditUserId: undefined
};

const data = reactive<PageData<visitorApplyInviteForm, visitorApplyInviteQuery>>({
  form: { ...initFormData },
  auditForm: { ...initAuditFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    type: undefined,
    visitReason: undefined,
    inviteUserId: undefined,
    startTime: undefined,
    endTime: undefined,
    params: {}
  },
  rules: {
    visitorApplyInviteId: [{ required: true, message: '主键不能为空', trigger: 'blur' }],
    remark: [{ required: true, message: '备注不能为空', trigger: 'blur' }],
    type: [{ required: true, message: '类型不能为空', trigger: 'change' }],
    visitorType: [{ required: true, message: '访客类型不能为空', trigger: 'blur' }],
    visitReason: [{ required: true, message: '造访事由不能为空', trigger: 'blur' }],
    inviteUserId: [{ required: true, message: '被访问者id不能为空', trigger: 'blur' }],
    startTime: [{ required: true, message: '访问开始时间不能为空', trigger: 'blur' }],
    endTime: [{ required: true, message: '访问结束时间不能为空', trigger: 'blur' }],
  },
  auditRules: {
    auditUserId: [{ required: true, message: '审批人不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules, auditForm,auditRules } = toRefs(data);

/***获取系统用户***/
const getUserList = async () => {
  loading.value = true;
  const res = await listUser();
  userList.value = res.rows;
  loading.value = false;
};


/** 查询访客申请邀约列表 */
const getList = async () => {
  loading.value = true;
  const res = await listvisitorApplyInvite(queryParams.value);
  visitorApplyInviteList.value = res.rows;
  total.value = res.total;
  loading.value = false;
  for(let item of visitorApplyInviteList.value){
    if(item.visitorUserList){
      let visitorNameList = item.visitorUserList.map(item => {
        return item.visitorName
      })
      // console.log('访客姓名列表：', visitorNameList)
      item.visitorNameList = visitorNameList.join('，')
    }if(item.visitorUserList){
      let visitorDeptNameList = item.visitorUserList.map(item => {
        return item.visitorDeptName
      })
      // console.log('访客姓名列表：', visitorDeptNameList)
      item.visitorDeptNameList = visitorDeptNameList.join('，')
    }
  }
};

/** 获取园区用户列表 */
const getAreaUserList = async () => {
  // TODO: 获取园区用户列表
  loading.value = true;
  const res = await listUserInfo(queryParams.value);
  areaUserList.value = res.rows;
  loading.value = false;
};

/**
 * 获取房间
 */
const getBuildingRoom = async ()=> {
  const res = await listparkBuildingRoom({type: 4});

  buildingRoomList.value = res.rows

  console.log('获取房间：', res)
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.shouAdd = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  visitorApplyInviteFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: visitorApplyInviteVO[]) => {
  ids.value = selection.map((item) => item.visitorApplyInviteId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.shouAdd = true;
  dialog.title = '添加访客申请邀约';
  // getUserList();
};

const submitAuditForm = () => {
  console.log('提交审批参数', auditForm.value);
  const res = addvisitorAudit(auditForm.value).finally(() => (buttonLoading.value = false));
  if (res.code === 200){
    proxy?.$modal.msgSuccess('操作成功');
  }else {
    proxy?.$modal.msgError('操作失败');
  }
  dialog.audit = false;
  getList();

};

/** 提交申请操作 */
const handleSubmit = async (row?: visitorApplyInviteVO) => {

  const loadingInstance = ElLoading.service({ fullscreen: true, text: '正在提交' })

  reset();
  const _visitorApplyInviteId = row?.visitorApplyInviteId || ids.value[0];
  const res = await getvisitorApplyInvite(_visitorApplyInviteId);
  Object.assign(form.value, res.data);
  form.value.status = 1;
  const updateRes = await updatevisitorApplyInvite(form.value).finally(() => {

  });
  if (updateRes.code === 200){
    await handleStartWorkFlow(res.data);
    proxy?.$modal.msgSuccess('操作成功');
  }else {
    proxy?.$modal.msgError('操作失败');
  }
  buttonLoading.value = false
  loadingInstance.close()
  await getList();
};



//提交申请,开始流程
const handleStartWorkFlow = async (data: visitorApplyInviteVO) => {
  try {
    submitFormData.value.tableName = 'visitor_apply_invite';
    submitFormData.value.businessKey = data.visitorApplyInviteId;
    //流程变量
    taskVariables.value = {
      entity: data,
      // userList: [1, 3],
      // userList2: [1, 3]
    };
    submitFormData.value.variables = taskVariables.value;
    const resp = await startWorkFlow(submitFormData.value);
    if (submitVerifyRef.value) {
      buttonLoading.value = false;
      submitVerifyRef.value.openDialog(resp.data.taskId);
    }
  } finally {
    buttonLoading.value = false;
  }
};


/** 查看按钮操作 */
const handleDetails = async (row?: visitorApplyInviteVO) => {
  reset();
  const _visitorApplyInviteId = row?.visitorApplyInviteId || ids.value[0];
  const res = await getvisitorApplyInvite(_visitorApplyInviteId);
  console.log('获取访客信息：', res)

  visitorApplyInviteInfo.value = res.data

  Object.assign(form.value, res.data);
  dialog.details = true;
  dialog.title = '查看访客申请';

  // let visitorUserRes = await request({ url: '/visitor/visitor-user/list', method: 'get', params: { visitorApplyInviteId: _visitorApplyInviteId } });
  // console.log('获取申请单访客信息：', visitorUserRes);

  // visitorUserList.value = visitorUserRes.rows
};

/** 提交按钮 */
const submitForm = () => {
  if (form.value.startTime !== undefined && form.value.startTime !== null && form.value.startTime.length == 2) {
    const start = form.value.startTime[0];
    const end = form.value.startTime[1];
    form.value.startTime = `${start}`;
    form.value.endTime = `${end}`;
  }
  console.log('提交参数', form.value);

  visitorApplyInviteFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.visitorApplyInviteId) {
        await updatevisitorApplyInvite(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addvisitorApplyInvite(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.shouAdd = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: visitorApplyInviteVO) => {
  const _visitorApplyInviteIds = row?.visitorApplyInviteId || ids.value;
  await proxy?.$modal.confirm('是否确认删除访客申请邀约编号为"' + _visitorApplyInviteIds + '"的数据项？').finally(() => (loading.value = false));
  await delvisitorApplyInvite(_visitorApplyInviteIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'visitor/visitor-apply-invite/export',
    {
      ...queryParams.value
    },
    `visitor-apply-invite_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
  getAreaUserList();
  getBuildingRoom()
});
</script>
<style lang="scss" scoped>
:deep(.el-card__header) {
  height: 60px;
}
:deep(.el-card__body) {
  height: calc(100% - 60px);
}
:deep(.pagination-container) {
  margin-top: 0;
}
.mb20 {
  margin-bottom: 20px;
}
.border-box {
  height: 600px;
  padding-top: 20px;

  border: 1px solid #0b0a0a;
  border-radius: 5px;
}
.el-input {
  width: 300px;
}
p {
    width: 240px;
    padding: 0;
    margin: 0;
  }
    .detail-title {
    margin-bottom: 10px;
    margin-left: 15px;
    border-left: 6px solid #409eff;
    padding-left: 10px;

  }
</style>
